package com.frontop.modules.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.frontop.constan.MessageConstant;
import com.frontop.modules.model.TUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
 * @author YangBoos
 * @title: HerringUserDetailsService
 * @projectName frontop-cloud
 * @description: 用户密码验证
 */
@Slf4j
@Component(value = "herringUserDetailsService")
public class HerringUserDetailsService implements UserDetailsService {


    @Resource
    private PasswordEncoder passwordEncoder;

    @Autowired
    TUserService tUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("username is:" + username);
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", username);
        TUser user = tUserService.getOne(queryWrapper);
        // 查询数据库操作
        if (user == null) {
            throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
        } else {
            // 用户权限在数据库中获取
            List<String> jurisdictionList = tUserService.getUserAllJurisdiction(username);
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for (String jurisdiction:jurisdictionList){
                authorities.add(new SimpleGrantedAuthority(jurisdiction));
            }
            // 通过用户名查询数据库获取加密后的密码
            String password = user.getPassword();
            if (user.getStatus().equals(0)) {
                throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
            }
            return new org.springframework.security.core.userdetails.User(username, password, authorities);
        }
    }
}